package com.stlm2.dems.service;

import com.stlm2.core.common.md5.MD5;
import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.dao.DdmShopDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.DdmShop;
import com.stlm2.dems.entity.User;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.user.dao.LowerDao;
import com.stlm2.dems.user.dao.RoleDao;
import com.stlm2.dems.user.dao.UserRoleDao;
import com.stlm2.dems.user.entity.*;
import com.stlm2.util.Memcached;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

import com.stlm2.dems.entity.ShopAdminUser;
import com.stlm2.dems.dao.ShopAdminUserDao;
import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("shopAdminUserService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class ShopAdminUserService extends BaseServiceImpl<ShopAdminUser> {

	@Resource
	private ShopAdminUserDao shopAdminUserDao;
	@Resource
	private UserDao userDao;
	@Resource
	private DdmShopDao ddmShopDao;
	@Resource
	private Memcached memcached;
	@Resource
	private RoleDao roleDao;
	@Resource
	private LowerDao lowerDao;
	@Resource
	private AccountDao accountDao;
	@Resource
	private UserRoleDao userRoleDao;

	@Override
	protected BaseDao <ShopAdminUser> getDao() {
		return shopAdminUserDao;
	}

	/*
	*获取我的店铺下拉框信息
	* zlq
	* token；
	 */
	public String getMyShopList(ModelMap model, String token){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		List<ShopAdminUser> shopAdminUserList= shopAdminUserDao.getByUserId(loginUser.getId());
		return CodeContent.getModelByCode(1, "", convertUsetShopList(shopAdminUserList));
	}

	public List<ModelMap> convertUsetShopList(List<ShopAdminUser> shopAdminUserList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (shopAdminUserList != null && shopAdminUserList.size() > 0) {
			for (ShopAdminUser shopAdminUser : shopAdminUserList) {
				ModelMap map = buildModelUserShopList(shopAdminUser);
				list.add(map);
			}
		}
		return list;
	}

	public ModelMap buildModelUserShopList(ShopAdminUser shopAdminUser) {
		ModelMap model = new ModelMap();
		model.put("shopId",shopAdminUser.getShopId());
		model.put("shopName",shopAdminUser.getDdmShopList().get(0).getName());
		return model;
	}

		/*
	*获取店铺成员列表
	* zlq
	* token；
	* page：页码
	* shopId:店铺ID
	* userStateValue：用户状态值
	 */
	public String getShopUserList(ModelMap model, String token,String page,String shopId,String userStateValue){
		PageView pageview = new PageView();
		int pageNo = 1;
		int pageSize = 20;
		if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
			pageNo = NumberUtils.toInt(page);
		}
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "", model);
		}
		if(!NumberUtils.isDigits(shopId)){
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		if(!NumberUtils.isDigits(userStateValue)){
			return CodeContent.getModelByCode(0, "用户状态不能为空", model);
		}
		if(UserState.getByIntValue(Integer.parseInt(userStateValue))==null){
			return CodeContent.getModelByCode(0, "用户状态不正确", model);
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(shopId));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
//		ShopAdminUser shopAdminUser=new ShopAdminUser();
//		shopAdminUser.setUserId(loginUser.getId());
//		shopAdminUser.setShopId(ddmShop.getId());
//		List<ShopAdminUser> shopAdminUserList=shopAdminUserDao.queryPageView(-1,-1,shopAdminUser).getRecords();
//		if(shopAdminUserList.size()==0){
//			return CodeContent.getModelByCode(0, ddmShop.getName() + "店铺您无权管理", model);
//		}
		UserRole userRole=userRoleDao.getByUserId(loginUser.getId());
		if(userRole==null){
			return CodeContent.getModelByCode(0, "用户角色不存在", model);
		}
		Role role=userRole.getRoleList().size()!=0?userRole.getRoleList().get(0):null;
		int roleInit = role!=null?role.getIsInitValue():IsInit.NotAllow.getIntValue();
		pageview=shopAdminUserDao.getByUserShopId(pageNo,pageSize,ddmShop.getId(), Integer.parseInt(userStateValue),roleInit);
		model.put("code",1);
		model.put("msg","success");
		if (pageview != null){
			model.put("datas",convertShopUserList(pageview.getRecords()));
			model.put("recordsTotal", pageview.getRowCount());
			model.put("totalPage", pageview.getPageCount());
			model.put("pageNow", pageview.getPageNow());
		}

		return new JSONObject(model).toString();
	}

	public List<ModelMap> convertShopUserList(List<ShopAdminUser> shopAdminUserList) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (shopAdminUserList != null && shopAdminUserList.size() > 0) {
			for (ShopAdminUser shopAdminUser : shopAdminUserList) {
				ModelMap map = buildModelShopUserList(shopAdminUser);
				list.add(map);
			}
		}
		return list;
	}
	public ModelMap buildModelShopUserList(ShopAdminUser shopAdminUser) {
		ModelMap model = new ModelMap();
		model.put("shopAdminUserId",shopAdminUser.getId());
		model.put("userId",shopAdminUser.getUserId());
		model.put("userRealName",shopAdminUser.getUserList().size()!=0?shopAdminUser.getUserList().get(0).getRealName():"");
		model.put("userPhone",shopAdminUser.getUserList().size()!=0?shopAdminUser.getUserList().get(0).getPhone():"");
		model.put("roleName",shopAdminUser.getRoleList().size()!=0?shopAdminUser.getRoleList().get(0).getName():"");
		if(shopAdminUser.getRoleList().size()!=0){
			model.put("userAccount",shopAdminUser.getUserList().get(0).getName());
			if(shopAdminUser.getRoleList().get(0).getIsInit().equals(IsInit.Allow)){
				model.put("ismodification",false);
			}else {
				model.put("ismodification",true);
			}
		}else {
			model.put("userAccount",shopAdminUser.getUserList().get(0).getName());
		}

		return model;
	}




	/*
	*创建后台店铺用户
	* zlq
	* @param  token
	* @param  userAccount：新用户账号
	* @param  realName：新用户名字
	* @param  roleId：新用户角色ID
	* @param  phone:手机号
	* @param  shopId:店铺ID
	 */
	public  String addShopUser(ModelMap model ,String token,String shopId,String userAccount,String realName,String roleId,String phone,String companyCode){
		if (StringUtils.isEmpty(token)) {
			return CodeContent.getModelByCode(-1, "请登录", model);
		}
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "请登录", model);
		}
		if (StringUtils.isEmpty(userAccount)) {
			return CodeContent.getModelByCode(0, "账号不能为空", model);
		}
		if (StringUtils.isEmpty(realName)) {
			return CodeContent.getModelByCode(0, "名字不能为空", model);
		}
		if (StringUtils.isEmpty(phone)) {
			return CodeContent.getModelByCode(0, "手机号不能为空", model);
		}
		if (!NumberUtils.isDigits(roleId)) {
			return CodeContent.getModelByCode(0, "角色不能为空", model);
		}
		if(!NumberUtils.isDigits(shopId)){
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(shopId));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}else if(!ddmShop.getState()){
			return CodeContent.getModelByCode(0, "无效的店铺", model);
		}
		Role role=roleDao.getById(Integer.parseInt(roleId));
		if(role==null){
			return CodeContent.getModelByCode(0, "角色ID不存在", model);
		}
		if(role.getIsInit().equals(IsInit.Allow)){
			return CodeContent.getModelByCode(0, "该用户不应分配此角色", model);
		}
		User newUser=userDao.getByName(userAccount);
		if(newUser!=null){
			return CodeContent.getModelByCode(0, "用户名已存在", model);
		}
		ShopAdminUser shopAdminUser=new ShopAdminUser();
		shopAdminUser.setShopId(ddmShop.getId());
		shopAdminUser.setUserId(loginUser.getId());
		List<ShopAdminUser> shopAdminUserList=shopAdminUserDao.queryPageView(-1,-1,shopAdminUser).getRecords();
		if(shopAdminUserList.size()==0){
			return CodeContent.getModelByCode(0, "您无权管理该店铺", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"addUser" );
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在10秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"addUser",10,"1");
		}

		int companyC=1;
		if(NumberUtils.isDigits(companyCode)){
			companyC=NumberUtils.toInt(companyCode);
		}

		newUser=new User();
		String password="123456";
		String md5Key = UUID.randomUUID().toString();
		String md5Password = MD5.encryptMD5(password.trim() + md5Key);

		newUser.setName(userAccount.trim());
		newUser.setCreateTime(new Date());
		newUser.setRealName(realName.trim());
		newUser.setUserKey(md5Key);
		newUser.setPassword(md5Password);
		newUser.setUserState(UserState.Normal);
		newUser.setUserType(UserType.Director);
		newUser.setSex(Sex.Privacy);
		newUser.setPhone(phone.trim());
		newUser.setUserLevel(UserLevel.Silver);
		newUser.setCompanyCode(companyC);
		userDao.add(newUser);
		newUser.setUserUpper(1+","+newUser.getId());
		userDao.modify(newUser);

		//上下级关系
		Lower lower=new Lower();
		lower.setUserId(1);
		lower.setLowerUserId(newUser.getId());
		lower.setState(true);
		lower.setCreateTime(new Date());
		lowerDao.add(lower);
		//userDao.userUpperLevel(7);
		//资金账户
		Account account=new Account();
		account.setAccountState(AccountState.Normal);
		account.setAccountType(AccountType.Customer);
		account.setAccountMoney(new BigDecimal(0));
		account.setAccountKey(md5Key);
		account.setUserId(newUser.getId());
		account.setReducedJiFen(new BigDecimal(0));
		account.setRemainJiFen(new BigDecimal(0));
		account.setTotalJiFen(new BigDecimal(0));
		accountDao.add(account);
		//添加角色
		UserRole userRole =new UserRole();
		userRole.setUserId(newUser.getId());
		userRole.setRoleId(Integer.parseInt(roleId));
		userRoleDao.add(userRole);

		shopAdminUser=new ShopAdminUser();
		shopAdminUser.setShopId(ddmShop.getId());
		shopAdminUser.setUserId(newUser.getId());
		shopAdminUser.setCreateUserId(loginUser.getId());
		shopAdminUser.setCreateTime(new Date());
		shopAdminUserDao.add(shopAdminUser);
		return CodeContent.getModelByCode(1, "", model);
	}

	/*
	*店铺添加成员(已存在的后台账号)
	* zlq
	* shopId:店铺ID
	* userId：用户ID
	 */
	public  String addShopMember(ModelMap model ,String token ,String shopId,String userId){
		User loginUser = userDao.getByToken(token);
		if (loginUser == null) {
			return CodeContent.getModelByCode(-1, "请登录", model);
		}
		UserRole loginUserRole=userRoleDao.getByUserId(loginUser.getId());
		if(loginUserRole==null){
			return CodeContent.getModelByCode(0, "无权添加", model);
		}
		if (!NumberUtils.isDigits(shopId)) {
			return CodeContent.getModelByCode(0, "店铺ID不能为空", model);
		}
		if (!NumberUtils.isDigits(userId)) {
			return CodeContent.getModelByCode(0, "用户ID不能为空", model);
		}
		DdmShop ddmShop=ddmShopDao.getById(Integer.parseInt(shopId));
		if(ddmShop==null){
			return CodeContent.getModelByCode(0, "店铺ID不存在", model);
		}
		if(!ddmShop.getState()){
			return CodeContent.getModelByCode(0, "无效店铺暂时无法添加成员", model);
		}
		User memberUser = userDao.getById(Integer.parseInt(userId));
		if(memberUser==null){
			return CodeContent.getModelByCode(0, "用户ID不存在", model);
		}
		if(memberUser.getUserState().equals(UserState.Invalid)){
			return CodeContent.getModelByCode(0, "用户已经无效", model);
		}
		UserRole memberUserRole=userRoleDao.getByUserId(loginUser.getId());
		if(memberUserRole==null){
			return CodeContent.getModelByCode(0, "该用户没有分配角色，无权添加", model);
		}
		if(loginUserRole.getRoleList().get(0).getIsInit().equals(IsInit.NotAllow)){
			if(memberUserRole.getRoleList().get(0).getIsInit().equals(IsInit.Allow)){
				return CodeContent.getModelByCode(0, "您的角色权限不允许给该用户分配店铺", model);
			}
		}
		ShopAdminUser shopAdminUser=new ShopAdminUser();
		shopAdminUser.setShopId(ddmShop.getId());
		shopAdminUser.setUserId(loginUser.getId());
		List<ShopAdminUser> shopAdminUserList=shopAdminUserDao.queryPageView(-1,-1,shopAdminUser).getRecords();
		if(shopAdminUserList.size()==0){
			return CodeContent.getModelByCode(0, "您无权管理该店铺", model);
		}
		//防止重复提交
		Object o = memcached.get(loginUser.getId()+"addShopMember" );
		if(o!=null){
			return CodeContent.getModelByCode(0, "您操作频繁，请在5秒后重试", model);
		}else {
			memcached.set(loginUser.getId()+"addShopMember",5,"1");
		}
		shopAdminUser=new ShopAdminUser();
		shopAdminUser.setShopId(ddmShop.getId());
		shopAdminUser.setUserId(memberUser.getId());
		shopAdminUserList=shopAdminUserDao.queryPageView(-1,-1,shopAdminUser).getRecords();
		if(shopAdminUserList.size()!=0){
			return CodeContent.getModelByCode(0, "用户已经在该店铺群组中", model);
		}
		shopAdminUser.setCreateUserId(loginUser.getId());
		shopAdminUser.setCreateTime(new Date());
		shopAdminUserDao.add(shopAdminUser);

		return CodeContent.getModelByCode(1, "", model);
	}

}